package de.bildung.koblenz.homeswitch;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import de.bildung.koblenz.adapter.SocketListItemAdapter;
import de.bildung.koblenz.homeswitch.entities.Room;
import de.bildung.koblenz.homeswitch.entities.Socket;
import de.bildung.koblenz.homeswitch.tasks.DiscoveryTask;
import de.bildung.koblenz.homeswitch.tasks.DiscoveryTask.IDiscoveryResult;
import de.bildung.koblenz.network.SocketUtil;

public class MainActivity extends FragmentActivity implements IDiscoveryResult {

	private static List<Room> roomList = new ArrayList<Room>();
	
	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	private SectionsPagerAdapter mSectionsPagerAdapter;
	
	private static SocketListItemAdapter adapter;
	
	private static Map<Room, List<Socket>> socketMap = new HashMap<Room, List<Socket>>();
	
	private static Handler refresher = new Handler();

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;
	
	/** SocketUtil zum Schalten der Sockets */
	private static SocketUtil util;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//		roomList.add(new Room("Default"));
		
		setContentView(R.layout.activity_main);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}
		
		

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a DummySectionFragment (defined as a static inner class
			// below) with the page number as its lone argument.
			Fragment fragment = new DummySectionFragment();
			Bundle args = new Bundle();
			args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
			fragment.setArguments(args);
			return fragment;
		}

		@Override
		public int getCount() {
			return roomList.size();
		}

		@Override
		public CharSequence getPageTitle(int position) {
			if (roomList.size() > position)
				return roomList.get(position).getName();
			else
				return null;
		}
		
	}

	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	public static class DummySectionFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public static final String ARG_SECTION_NUMBER = "section_number";

		public DummySectionFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			Bundle bundle = getArguments();
			int number = bundle.getInt(ARG_SECTION_NUMBER);
			Room room = roomList.get(number-1);
			ListView listView = new ListView(getActivity());
			adapter = new SocketListItemAdapter(getActivity(), util);
			listView.setAdapter(adapter);
			List<Socket> sockets = socketMap.get(room);
			if (sockets != null) {
				adapter.clear();
				adapter.addAll(sockets);
				adapter.notifyDataSetChanged();
			}
			return listView;
		}
		
		
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menu_search_server:
				DiscoveryTask task = new DiscoveryTask(this, this);
				task.execute();
				break;
			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void discoveryFinished(String ip, String port) {
		if (ip == null) return;
		try {
			util = new SocketUtil(ip, port);
			List<Socket> socketList = util.getAllSwitches();
			roomList.clear();
			roomList.addAll(util.getAllRooms());
			socketMap.clear();
			for (Room room : roomList) {
				List<Socket> list = new ArrayList<Socket>();
				for (Socket socket : socketList) {
					if (socket.getRoomId() == room.getId()) {
						list.add(socket);
					}
				}
				socketMap.put(room, list);
			}
			final List<Socket> currentSocketList = new ArrayList<Socket>();
			if (roomList.size() > 0) {
				currentSocketList.addAll(socketMap.get(roomList.get(0)));
			}
			Runnable r = new Runnable() {
				
				@Override
				public void run() {
					mSectionsPagerAdapter.notifyDataSetChanged();
				}
			};
			refresher.post(r);	
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	
	

}
